#include "servicetreewidget.h"
#include <QMenu>
#include <QMouseEvent>
#include <QInputDialog>
#include <QMessageBox>
#include <QHeaderView>
#include <QDir>
#include <QDebug>

ServiceTreeWidget::ServiceTreeWidget(QWidget *parent) : QTreeWidget(parent)
{
    QStringList lstHeader;
    lstHeader.clear();
    lstHeader<<tr("Service&Interface");
    lstHeader<<tr("Discribe");

    this->setColumnCount(lstHeader.count());
    this->setHeaderLabels(lstHeader);
    this->header()->setDefaultAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
}

void ServiceTreeWidget::generateService(QTreeWidgetItem *pItem, const QString &path, const QString &bundleName)
{
    QDir fileDir(path);

    QFile tempFile(":/ModelFile/BundleDesigner/service.temp");
    if(!tempFile.open(QIODevice::ReadOnly))
    {
        qWarning()<<"tempfile open failed";
        return;
    }

    QTextStream in(&tempFile);

    QString serviceName = pItem->data(0,Qt::DisplayRole).toString();
    QStringList sInterfaceList;
    sInterfaceList.clear();
    for(int i=0; i<pItem->childCount(); ++i)
    {
        QTreeWidgetItem* pChiItem = pItem->child(i);
        if(nullptr == pChiItem)continue;
        QString sInterface = pChiItem->data(0,Qt::DisplayRole).toString();
        if(sInterface.isEmpty())continue;
        sInterfaceList.append(sInterface);
    }

#if 1// interface file
    QFile interfaceFile(fileDir.absolutePath()+"/i"+serviceName.toLower()+".h");
    if(!interfaceFile.open(QIODevice::WriteOnly))
    {
        qWarning()<<"interfaceFile open failed";
        return;
    }
    QTextStream intout(&interfaceFile);
    int nRunFlag = 0;// 0表示还没找到开始，1表示已经开始，还未结束，2表示已经结束，事实上，不会出现2
    while(!in.atEnd())
    {
        QString sLine = in.readLine();
        if(nRunFlag == 0)
        {
            if(sLine.contains("[serviceinterfaceheaderbegin]"))
            {
                nRunFlag = 1;
            }
            continue;
        }
        else if(nRunFlag == 1)
        {
            if(sLine.contains("[serviceinterfaceheaderend]"))
            {
                nRunFlag = 2;
                break;
            }
            else if(sLine.contains("[interfacebody]"))
            {
                foreach (QString s, sInterfaceList) {
                    QString sOut = sLine;
                    sOut = sOut.replace("[interfacebody]",s);
                    intout<<sOut<<"\r\n";
                }
                continue;
            }
            else
            {
                QString sOut = sLine;
                sOut = sOut.replace("[name]",serviceName);
                sOut = sOut.replace("[name_lower]",serviceName.toLower());
                sOut = sOut.replace("[name_upper]",serviceName.toUpper());
                sOut = sOut.replace("[bundlename]",bundleName);

                intout<<sOut<<"\r\n";

                continue;
            }
        }
        else
        {
            break;
        }

    }
    interfaceFile.close();

#endif

#if 2// header file
    QFile headerFile(fileDir.absolutePath()+"/"+serviceName.toLower()+".h");
    if(!headerFile.open(QIODevice::WriteOnly))
    {
        qWarning()<<"headerFile open failed";
        return;
    }
    QTextStream headerout(&headerFile);
    int nRunHeaderFlag = 0;// 0表示还没找到开始，1表示已经开始，还未结束，2表示已经结束，事实上，不会出现2
    while(!in.atEnd())
    {
        QString sLine = in.readLine();
        if(nRunHeaderFlag == 0)
        {
            if(sLine.contains("[serviceheaderbegin]"))
            {
                nRunHeaderFlag = 1;
            }
            continue;
        }
        else if(nRunHeaderFlag == 1)
        {
            if(sLine.contains("[serviceheaderend]"))
            {
                nRunHeaderFlag = 2;
                break;
            }
            else if(sLine.contains("[interfacebody]"))
            {
                foreach (QString s, sInterfaceList) {
                    QString sOut = sLine;
                    sOut = sOut.replace("[interfacebody]",s);
                    headerout<<sOut<<"\r\n";
                }
                continue;
            }
            else
            {
                QString sOut = sLine;
                sOut = sOut.replace("[name]",serviceName);
                sOut = sOut.replace("[name_lower]",serviceName.toLower());
                sOut = sOut.replace("[name_upper]",serviceName.toUpper());
                sOut = sOut.replace("[bundlename]",bundleName);

                headerout<<sOut<<"\r\n";

                continue;
            }
        }
        else
        {
            break;
        }

    }
    headerFile.close();

#endif

#if 3// source file
    QFile sourceFile(fileDir.absolutePath()+"/"+serviceName.toLower()+".cpp");
    if(!sourceFile.open(QIODevice::WriteOnly))
    {
        qWarning()<<"sourceFile open failed";
        return;
    }
    QTextStream cppout(&sourceFile);
    int nRunCppFlag = 0;// 0表示还没找到开始，1表示已经开始，还未结束，2表示已经结束，事实上，不会出现2
    while(!in.atEnd())
    {
        QString sLine = in.readLine();
        if(nRunCppFlag == 0)
        {
            if(sLine.contains("[servicecppbegin]"))
            {
                nRunCppFlag = 1;
            }
            continue;
        }
        else if(nRunCppFlag == 1)
        {
            if(sLine.contains("[servicecppend]"))
            {
                nRunCppFlag = 2;
                break;
            }
            else if(sLine.contains("[interfacebody]"))
            {
                foreach (QString s, sInterfaceList) {
                    QString sOut = QString("%1\r\n{\r\n\r\n}\r\n").arg(s);
                    cppout<<sOut<<"\r\n";
                }
                continue;
            }
            else
            {
                QString sOut = sLine;
                sOut = sOut.replace("[name]",serviceName);
                sOut = sOut.replace("[name_lower]",serviceName.toLower());
                sOut = sOut.replace("[name_upper]",serviceName.toUpper());
                sOut = sOut.replace("[bundlename]",bundleName);

                cppout<<sOut<<"\r\n";

                continue;
            }
        }
        else
        {
            break;
        }

    }
    sourceFile.close();
#endif

    tempFile.close();
}

void ServiceTreeWidget::generateServiceFiles(const QString &path,const QString &bundleName)
{
    if(path.isEmpty())return;

    if(this->topLevelItemCount() < 1)
        return;

    for (int i=0; i<this->topLevelItemCount(); ++i) {
        QTreeWidgetItem* pTopItem = this->topLevelItem(i);
        if(pTopItem->childCount() < 1)
            continue;

        generateService(pTopItem,path,bundleName);
    }


}

void ServiceTreeWidget::slot_AddService()
{
    QString sClassName = QInputDialog::getText(this,tr("Input Service Class"),tr("ServiceClass"),QLineEdit::Normal);

    if(sClassName.isEmpty())
        return;

    QTreeWidgetItem* pTopItem = new QTreeWidgetItem();
    pTopItem->setData(0,Qt::DisplayRole,sClassName);
    pTopItem->setIcon(0,QIcon(":/default/icon/warning.png"));
    pTopItem->setToolTip(0,tr("there is no interface for the service class"));
    this->addTopLevelItem(pTopItem);
}

void ServiceTreeWidget::slot_RemoveService()
{
    QTreeWidgetItem* pCurItem = this->currentItem();
    if(nullptr == pCurItem)
        return;

    this->takeTopLevelItem(this->indexOfTopLevelItem(pCurItem));

    delete pCurItem;
    pCurItem = nullptr;
}

void ServiceTreeWidget::slot_AddInterface()
{
    QTreeWidgetItem* pCurItem = this->currentItem();
    if(nullptr == pCurItem)
    {
        QMessageBox::warning(this,tr("warning"),tr("please select service first"));
        return;
    }

    QString sInterface = QInputDialog::getText(this,tr("Input Interface Context"),tr("Interface"),QLineEdit::Normal);

    if(sInterface.isEmpty())
        return;
    QString sInterfaceDis = QInputDialog::getText(this,tr("Interface Discribe"),tr("Discribe"),QLineEdit::Normal);

    QTreeWidgetItem* pInterfaceItem = new QTreeWidgetItem();
    pInterfaceItem->setData(0,Qt::DisplayRole,sInterface);
    pInterfaceItem->setData(1,Qt::DisplayRole,sInterfaceDis);

    pCurItem->addChild(pInterfaceItem);
    pCurItem->setIcon(0,QIcon(":/default/icon/tick.png"));
    pCurItem->setExpanded(true);
}

void ServiceTreeWidget::slot_RemoveInterface()
{
    QTreeWidgetItem* pCurItem = this->currentItem();
    if(nullptr == pCurItem)
    {
        return;
    }

    QTreeWidgetItem* pTopItem = pCurItem->parent();
    if(nullptr == pTopItem)
        return;

    pTopItem->takeChild(pTopItem->indexOfChild(pCurItem));
    delete pCurItem;
    pCurItem = nullptr;

    if(pTopItem->childCount()<1)
    {
        pTopItem->setIcon(0,QIcon(":/default/icon/warning.png"));
    }
}



void ServiceTreeWidget::mousePressEvent(QMouseEvent *event)
{
    QTreeWidgetItem* pItem = itemAt(event->pos());
    if(nullptr != pItem)
    {
        this->setCurrentItem(pItem);
    }

    if(event->button() == Qt::RightButton)
    {
        QMenu menu;
        menu.addAction(QIcon(),tr("AddService"),this,SLOT(slot_AddService()));

        if(nullptr != pItem)
        {
            if(pItem->parent() == nullptr)
            {
                menu.addAction(QIcon(),tr("AddInterface"),this,SLOT(slot_AddInterface()));
                menu.addAction(QIcon(),tr("RemoveService"),this,SLOT(slot_RemoveInterface()));
            }
            else
            {
                menu.addAction(QIcon(),tr("RemoveInterface"),this,SLOT(slot_RemoveService()));
            }

        }
        menu.exec(event->globalPos());

    }
    QTreeWidget::mousePressEvent(event);
}
